<template>
	<view class="shop-cart" :class="themeName">
		<view class="main" :style="[mainStyle]">
			<!-- 商品卡片 -->
			<block v-for="(item, index) in cartLists" :key="index">
				<view class="cart-list">
					<view class="cart-item bg-white"
						:class="{ invalid: item.cart_status != 0,nostock:item.not_enough_stock }">
						<!-- 商品头部 -->
						<view class="row-between flex select" v-if="item.cart_status == 0">
							<u-checkbox label-size="28rpx" :active-color="themeColor" v-model="item.selected"
								@change="changeGoodsStatus(item.selected, item.id)" :label-disabled="false"
								shape="circle" v-if="item.is_gifts == 0 || cloud_shop_enabled">
								<text class="normal">{{$zhTran('选择')}}</text>
							</u-checkbox>
							<view v-else>
								<view class="gfa-tag">{{$zhTran('赠品')}}</view>
							</view>
							<view @click="changeDelPopup(item.id)">
								<image class="icon-xl" style="width: 56rpx; height: 56rpx"
									:src="$getImageUri('resource/image/shopapi/uniapp/icon_del.png')" />
							</view>
						</view>

						<!-- 商品头部已失效的状态 -->
						<view class="select row-between flex sm muted" v-else>
							{{$zhTran('已失效')}}
							<view :data-cartid="item.cart_id" @click="changeDelPopup(item.id)">
								<image class="icon-xl" style="width: 56rpx; height: 56rpx"
									:src="$getImageUri('resource/image/shopapi/uniapp/icon_del.png')" />
							</view>
						</view>

						<!-- 商品的主内容 -->
						<router-link :to="`/bundle2/pages/goods_detail/goods_detail?id=${item.goods_id}`">
							<view class="flex" style="padding: 20rpx">
								<u-image width="180rpx" height="180rpx" :src="item.goods.image" />
								<view class="m-l-20" style="flex: 1">
									<view class="line-2 nr">{{ item.goods.name }}</view>
									<view class="muted xs line-1 m-t-10" v-if="pagesComment.show_cart_goods_tag == 1">
										<u-image width="80rpx" height="40rpx" :src="item.goods.tag_desc"
											v-if="item.goods.tag_desc != ''" />
									</view>
									<view class="muted xs line-1 m-t-10">
										{{ item.goods_item.spec_value_str }}
									</view>
									<view class="muted xs line-1 m-t-10" v-if="pagesComment.show_cart_goods_code == 1"
										:style="{
                      color: pagesComment.cart_goods_code_color,
                    }">
										{{$zhTran('编码：')}}{{ item.goods.code }}
									</view>
									<view class="muted xs line-1 m-t-10" v-if="pagesComment.show_cart_goods_model == 1"
										:style="{
                      color: pagesComment.cart_goods_model_color,
                    }">
										{{$zhTran('型号：')}}{{ item.goods.goods_model }}
									</view>
									<view class="row-between flex m-t-20">
										<view class="price flex primary">
											<view
												v-if="pagesComment.show_price_type*1==0 || !Number(item.goods_item.member_price)">
												<text :style="{color:themeColor}"
													v-if="pagesComment.show_price_text">{{$zhTran('销售价：')}}</text>
												<price :content="item.goods_item.sell_price" :color="themeColor"
													mainSize="36rpx" minorSize="28rpx"
													:prefix="!shop_price_show?'':price_symbol"></price>
											</view>
											<view
												v-if="pagesComment.show_price_type*1==1 && Number(item.goods_item.member_price)">
												<text :style="{color:themeColor}"
													v-if="pagesComment.show_price_text">{{$zhTran('会员价：')}}</text>
												<price :content="item.goods_item.member_price" :color="themeColor"
													mainSize="36rpx" minorSize="28rpx" :prefix="price_symbol"></price>
											</view>
										</view>
										<view class="cartNum" @tap.stop=""
											v-if="item.is_gifts == 0 || cloud_shop_enabled">
											<u-number-box :disabled="item.cart_status != 0" v-model="item.goods_num"
												:min="item.min||1" :step="item.step||1" async-change positiveInteger
												:size="36" @change="countChange($event, item.id)" />
										</view>
									</view>
									<view class="row-between flex m-t-20" v-if="item.aux_id > 0">
										{{$zhTran('单位：')+item.aux_info.aux_unit_name+'( '+item.aux_info.coefficient+item.aux_info.base_unit_name+' )'}}
									</view>

									<view class="nostock-alert flex row-right m-t-20" v-if="item.not_enough_stock">
										<view class="m-t-20">加购商品数已超出最大库存</view>
									</view>
								</view>
							</view>
						</router-link>
					</view>
				</view>
			</block>

			<!-- 购物车空状态 -->
			<view class="cart-null bg-white m-b-20" style="padding: 80rpx 0 50rpx"
				v-if="isLogin && cartLists.length == 0">
				<image class="img-null" :src="$getImageUri('resource/image/shopapi/uniapp/empty/cart.png')"></image>
				<view class="muted m-b-20">{{$zhTran('购物车暂无任何商品~')}}</view>
				<view class="br60 btn flex row-center" @tap="goShoping">{{$zhTran('去逛逛')}}</view>
			</view>

			<!-- 是否登录的空状态 -->
			<view v-if="!isLogin" class="login column-center" style="padding: 200rpx 0 50rpx">
				<image class="img-null" :src="$getImageUri('resource/image/shopapi/uniapp/empty/cart.png')"></image>
				<view class="muted mt20">{{$zhTran('登录后才能查看购物车哦')}}</view>
				<navigator class="white br60 row-center btn" url="/bundle2/pages/login/login">
					<text>{{$zhTran('去登录')}}</text>
				</navigator>
			</view>

			<!-- diy组件区 -->
			<block v-for="(item, cIndex) in pagesData" :key="cIndex">
				<template v-if="item.name == 'goodsrecom'">
					<w-goodsrecom v-show="item.show" :content="item.content" :styles="item.styles"
						@refreshList="refreshList" />
				</template>
			</block>
			<w-jishuzhichi />
		</view>

		<!-- 满赠活动提示 -->
		<view class="footer footer-gfa flex bg-white" v-if="give_full_limit > 0 && !cloud_shop_enabled">
			<view class="flex">
				<view class="gfa-tag m-r-10">{{$zhTran('满赠')}}</view>
				<text v-if="give_full_type == 1">{{$zhTran('已购满'+give_full_limit+'件，可领取赠品')}}</text>
				<text v-if="give_full_type == 2">{{$zhTran('已购满'+give_full_limit+'元，可领取赠品')}}</text>
			</view>
			<view style="color: rgba(255, 44, 60, 1);" @tap="goGiveList">{{$zhTran('查看更多')}}
				<u-icon name="arrow-right" class="nr" style="margin-left: auto" />
			</view>
		</view>

		<!-- 底部结算栏 -->
		<view class="footer flex bg-white">
			<!-- left -->
			<checkbox-group class="normal">
				<u-checkbox label-size="28rpx" @change="changeAllSelect" id="checkAll" value="all"
					:active-color="themeColor" v-model="isSelectedAll" :label-disabled="false"
					:disabled="selectAllDisabled" shape="circle">
					<text class="normal">{{$zhTran('全选')}}</text>
				</u-checkbox>
			</checkbox-group>
			<!-- <view class="">
                删除
            </view> -->
			<!-- right -->
			<view class="all-price nr m-r-20 flex row-right">
				<view>{{$zhTran('合计：')}}</view>
				<price :content="total_amount || 0" :color="themeColor" mainSize="36rpx" minorSize="28rpx"
					:prefix="price_symbol"></price>
			</view>
			<view class="right-btn br60 white" v-if="getResultBtn" @tap="goToConfirm">{{$zhTran('去结算')}}</view>
			<view class="right-btn br60 lighter" style="background: #f2f2f2" v-else>{{$zhTran('去结算')}}</view>
		</view>

		<!-- 是否删除商品的弹窗 -->
		<u-modal v-model="delPopup" :showCancelButton="true" :comfirm-text="$zhTran('狠心删除')" :confirm-color="themeColor"
			:show-title="false" @confirm="goodsDelete">
			<view style="padding-top: 40rpx" class="flex row-center">
				<!-- <image class="icon-lg" :src="$getImageUri('resource/image/shopapi/uniapp/icon_warning.png')" /> -->
				<view style="margin: 50rpx 0">{{$zhTran('确认删除该商品吗？')}}</view>
			</view>
		</u-modal>
		<tabbar />

		<!-- 加载中 -->
		<u-mask :show="isChangeLoading" :mask-click-able="false" :custom-style="{ background: 'rgba(0, 0, 0, 0)' }">
		</u-mask>
		<view class="loading" v-if="isChangeLoading">
			<u-loading size="40" :color="themeColor"></u-loading>
			<view class="white m-t-20">{{$zhTran(' 加载中... ')}}</view>
		</view>

	</view>
</template>

<script>
	import {
		apiCartLists, //商品列表
		apiCartDel, //商品删除
		apiCartCountChange, //商品数量改变
		apiCartSelectChange, //选择商品
		apiGetPage, //获取当前diy页面
	} from "@/api/store";
	import {
		OrderTypeEnum
	} from "@/utils/enum";
	import {
		trottle
	} from "@/utils/tools";
	import {
		apiGiveFullActiviryChange
	} from "@/api/give_full_activity";
	import Cache from '@/utils/cache'

	export default {
		name: "ShopCart",

		data() {
			return {
				pagesData: [], //diy的组件
				cartLists: [], //购物车数据
				cartListsId: [], //购物车数据的所有ID
				total_amount: "", //购物车合计金额
				delPopup: false, //是否弹出删除商品的弹窗
				cart_id: 0, //删除的购物车ID
				isSelectedAll: false, //是否全选
				isChangeLoading: true, //是否是操作请求中状态
				price_symbol: "￥",
				pagesComment: {},
				give_full_limit: 0,
				give_full_type: 0,
				shop_price_show: 1,
				order_enabled: 1,
				cloud_shop_enabled: Cache.get('cloud_shop_enabled'),
			};
		},

		methods: {
			// 获取购物车数据列表
			getCartList() {
				return apiCartLists({
					clsp_id: Cache.get('clsp_id')
				}).then((res) => {
					this.total_amount = res.total_amount;
					this.price_symbol = res.price_symbol;
					this.shop_price_show = res.shop_price_show
					this.order_enabled = res.order_enabled
					this.give_full_type = res.give_full_type;
					this.give_full_limit = res.give_full_limit;
					res.lists.forEach((item, index) => {
						res.lists[index].selected = item.selected == 1 ? true : false;
					});
					this.cartLists = this.$zhTran(res.lists);
					this.baseSelect(res.lists);
					this.$store.dispatch("getCartNum");

					return Promise.resolve();
				}).catch((err) => {
					console.log('cart list', err)
				}).finally(() => {
					this.isChangeLoading = false;
				});
			},

			// 初始化商品的选中状态
			baseSelect(data) {
				this.cartListsId = [];
				const res = data.filter((el) => {
					this.cartListsId.push(el.id);
					return el.selected == false;
				});

				this.isSelectedAll = true;
				this.goodsListActive.map((item) => {
					if (!item.selected) this.isSelectedAll = false;
				});
				// if (res.length == 0) {
				// 	this.isSelectedAll = true;
				// } else {
				// 	this.isSelectedAll = false;
				// }
			},

			// 商品数量的修改
			countChange({
				value
			}, id) {

				let data = this.cartLists.filter(item => item.id == id)[0]
				let coefficient = 1,
					aux_info = data.aux_info || {}
				if (Object.keys(aux_info).length > 0) {
					coefficient = aux_info.coefficient || 1
				}
				if (Number(data.goods_item.limit_buy) > 0 && Number(data.goods_item.limit_buy) > value * coefficient) {
					this.$toast({
						title: '最小起订量为' + data.goods_item.limit_buy + data.goods.unit_desc
					})
					return
				}

				this.isChangeLoading = true;
				apiCartCountChange({
						cart_id: id,
						goods_num: value,
					})
					.then((res) => {
						this.$store.dispatch("getCartNum");
					})
					.finally(() => {
						this.getCartList();
					});
			},

			// 弹窗拿到当前需要删除的商品购物车ID
			changeDelPopup(cart_id) {
				this.delPopup = true;
				this.cart_id = cart_id;
			},

			// 删除购物车的商品
			async goodsDelete() {
				this.isChangeLoading = true;
				await apiCartDel({
					cart_id: this.cart_id,
				});
				await this.getCartList();
				this.$toast({
					title: this.$zhTran("删除成功"),
				});
			},

			// 单选
			changeGoodsStatus(status, id) {
				this.isChangeLoading = true;
				status = status == 1 ? 0 : 1;
				apiCartSelectChange({
					cart_id: [id],
					selected: status,
				}).then((res) => {
					this.getCartList();
				});
			},

			// 全选商品
			changeAllSelect() {
				this.isChangeLoading = true;
				const status = this.isSelectedAll == true ? 0 : 1;
				const cartIDs = this.goodsListActive.map((item) => item.id);
				apiCartSelectChange({
					cart_id: cartIDs,
					selected: status,
				}).then((res) => {
					this.getCartList();
				});
			},

			// 去购物
			goShoping() {
				this.$Router.replaceAll("/pages/index/index");
			},

			goGiveList() {
				this.$Router.push({
					path: "/bundle2/pages/give_full_activity/give_full_goods_list",
					query: {
						give_full_limit: this.give_full_limit,
						give_full_type: this.give_full_type,
					}
				});
			},

			// 去结算
			goToConfirm() {
				if (!this.shop_price_show) {
					uni.showModal({
						content: this.$zhTran('该会员组无权限查看商品价格，无法下单'),
						confirmColor: this.themeColor,
						confirmText: this.$zhTran('确定'),
						showCancel: false
					})
					return false
				}
				if (!this.order_enabled) {
					uni.showModal({
						content: this.$zhTran('该会员组无权下单'),
						confirmColor: this.themeColor,
						confirmText: this.$zhTran('确定'),
						showCancel: false
					})
					return false
				}
				const carts = this.cartLists.filter((item) => item.selected).map((item) => item.id);
				if (carts.length == 0)
					return this.$toast({
						title: this.$zhTran("请选择商品"),
					});
				// this.$Router.push({
				// 	path: "/bundle2/pages/goods_order/goods_order",
				// 	query: {
				// 		from: OrderTypeEnum["GOODS"],
				// 		payload: {
				// 			source: "cart",
				// 			cart_id: carts,
				// 		},
				// 	},
				// });
				var that = this
				uni.navigateTo({
					url: "/bundle2/pages/goods_order/goods_order",
					events: {
						reCountCarNum: function(o) {
							that.getCartList()
							that.$store.dispatch("getCartNum");
						}
					},
					success(res) {
						res.eventChannel.emit("receiveData", {
							from: OrderTypeEnum["GOODS"],
							payload: {
								source: "cart",
								cart_id: carts,
							},
						});
					}
				});
			},

			// 去首页
			changeTab() {
				this.$Router.replaceAll({
					path: "/pages/index/index",
				});
			},

			getPage() {
				apiGetPage({
					type: 4,
				}).then((res) => {
					const {
						common: {
							title
						},
						common,
						content,
					} = this.$zhTran(res);
					uni.setNavigationBarTitle({
						title,
					});
					this.pagesData = content;
					this.pagesComment = common;
				});
			},
			refreshList() {
				this.getCartList()
			},
		},
		computed: {
			cartNum() {
				return this.$store.state.cart.cartNum;
			},
			getResultBtn() {
				const carts = this.cartLists.filter((item) => item.selected).map((item) => item.id);
				if (carts.length == 0) {
					this.isSelectedAll = false;
					return false;
				} else {
					return true;
				}
			},

			// 可售卖商品列表
			goodsListActive() {
				return this.cartLists.filter((item) => item.cart_status == 0) || [];
			},

			// 是否可全选操作
			selectAllDisabled() {
				return !!!this.goodsListActive.length;
			},
			mainStyle() {
				var pb = 115

				if (this.give_full_limit > 0 && !this.cloud_shop_enabled) {
					pb = 215
				}

				return {
					'padding-bottom': `${pb}rpx`
				}
			},
		},
		async onShow() {
			// this.getCartNum()
			await this.getCartList();
			if (this.isLogin) {
				this.getPage();
			}

			if (Cache.get('cloud_shop_enabled'))
				uni.hideHomeButton()
		},

		created() {
			this.isChangeLoading = true;
			this.countChange = trottle(this.countChange, 200);
		},
	};
</script>
<style lang="scss">
	.shop-cart {
		position: relative;

		.loading {
			position: fixed;
			left: 39vw;
			top: 35vh;
			height: 170rpx;
			width: 170rpx;
			border-radius: 20rpx;
			background: rgba(0, 0, 0, 0.5);
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
		}
	}

	.cart-list {
		.cart-item {
			margin: 20rpx 20rpx 0;
			border-radius: 10rpx;

			&.invalid {
				opacity: 0.7;
				// background-color: #999;
				// @include background_color();
			}

			&.nostock {
				border: 2rpx solid rgba(255, 44, 60, 1);
			}

			.nostock-alert {
				view {
					background-color: rgba(255, 238, 239, 1);
					color: rgba(255, 44, 60, 1);
					padding: 10rpx;
				}
			}
		}

		.select {
			height: 80rpx;
			padding: 0 20rpx;
			// @include border_color();
			// border-style: solid;
		}
	}

	.cart-null {
		text-align: center;

		.btn {
			@include font_color();
			@include border_color();
			border-width: 1rpx;
			border-style: solid;
			width: 184rpx;
			margin-left: auto;
			margin-right: auto;
			padding: 8rpx 24rpx;
		}
	}

	.footer {
		left: 0;
		margin-bottom: 100rpx;
		bottom: calc(env(safe-area-inset-bottom));
		width: 100%;
		z-index: 20;
		height: 100rpx;
		position: fixed;
		padding: 0 24rpx;
		box-sizing: border-box;
		background-color: #ffffff;
		box-shadow: 0px 0px 12px rgba(0, 0, 0, 0.1);

		.all-price {
			text-align: right;
			flex: 1;
		}

		.right-btn {
			padding: 13rpx 45rpx;
			@include background_color();
		}
	}

	.footer-gfa {
		bottom: calc(env(safe-area-inset-bottom) + 100rpx);
		font-size: 26rpx;
		justify-content: space-between;
	}


	.gfa-tag {
		width: 80rpx;
		height: 40rpx;
		border: 1rpx solid red;
		border-radius: 6rpx;
		color: rgba(255, 44, 60, 1);
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.login {
		// height:calc(100vh - var(--window-bottom));
		background: #fff;
		text-align: center;

		.btn {
			width: 280rpx;
			line-height: 70rpx;
			margin: 40rpx auto 0;
			background-color: #09bb07;

			image {
				width: 50rpx;
				height: 50rpx;
			}
		}
	}
</style>